/**
 * 存放一些通用的方法
 */

import classNames from 'classnames';
import crypto from 'crypto';

export function isValidURL(url: string): boolean {
  try {
    new URL(url);
    return true;
  } catch (_) {
    return false;
  }
}

export function parseMarkdownTable(markdown: string): { headers: string[]; rows: string[][] } {
  const lines = markdown.split('\n');
  const tableLines = lines.filter((line) => line.trim().startsWith('|'));
  const rows = tableLines.map((line) =>
    line
      .trim()
      .split('|')
      .filter((cell) => cell.trim() !== '')
      .map((cell) => cell.trim()),
  );

  const headers = rows[0]?.every((cell) => cell.startsWith('-')) ? [] : rows.shift() || [];
  return { headers, rows };
}

export function detectTableHeader(markdown: string): {
  isTable: boolean;
  hasHeader: boolean;
  lineNumber: number;
  columnCount: number;
} {
  const pattern = /\|\s*-+/g;
  const lines = markdown.split('\n');
  let isTable = false;
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim();
    if (line.startsWith('|') && line.endsWith('|')) {
      isTable = true;
      const nextLine = lines[i + 1];
      const columns = line.split('|');
      const columnCount = columns.slice(1, -1).length;
      if (nextLine && nextLine.trim().startsWith('|') && nextLine.includes('-')) {
        const nexColumnLen = nextLine.match(pattern)?.length;
        if (columnCount == nexColumnLen) {
          return { isTable, hasHeader: true, lineNumber: i, columnCount };
        }
      }
      return { isTable, hasHeader: false, lineNumber: i, columnCount };
    }
  }
  return { isTable, hasHeader: false, lineNumber: -1, columnCount: 0 };
}

export function addTableHeader(markdown: string): string {
  try {
    const lines = markdown.split('\n');
    const hasTable = lines.some((line) => line.trim().startsWith('|') && line.trim().endsWith('|'));

    if (!hasTable) {
      console.log('No table found in the text.');
      return markdown;
    }

    const { isTable, hasHeader, lineNumber, columnCount } = detectTableHeader(markdown);

    if (hasHeader) {
      console.log('Table already has a header.');
      return markdown;
    }

    const tableStartLine = lineNumber;
    // const tableData = parseMarkdownTable(markdown);
    if (!isTable) {
      console.log('No table rows found.');
      return markdown;
    }

    const newHeader = Array(columnCount)
      .fill('')
      .map((h, i) => `${h}`)
      .join(' | ');
    const separator = Array(columnCount).fill('---').join(' | ');

    lines.splice(tableStartLine, 0, `| ${newHeader} |`, `| ${separator} |`);

    return lines.join('\n');
  } catch (error) {
    console.error(error);
    return markdown;
  }
}

export const removeThinkTags = (text: string) => {
  // 使用正则表达式匹配<think>标签及其内容，并将其替换为空字符串
  return text
    ?.replace(/<think>.*?<\/think>/gs, '')
    ?.replace(/<span class="eaitip".*?<\/span>/gs, '');
};

export const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * 16) | 0;
    const v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

export const getFilenameFromPath = (filePath: string): string => {
  return filePath?.split('/')?.pop() || '';
};

export const fetchConfigStatus = (configList: any, configName: string, defaultStatus: boolean = false) => {
  const configItem = configList?.find((config: any) => config.name === configName);
  if (!configItem) return defaultStatus;
  const configStatus = configItem?.default_value === '1' || configItem?.default_value === true;
  return configStatus;
};

/**
 * 类名合并工具函数
 * 基于 classnames 库，支持条件类名和类名合并
 * @param inputs 类名输入，支持字符串、对象、数组等多种格式
 * @returns 合并后的类名字符串
 */
export const cn = (...inputs: classNames.ArgumentArray) => {
  return classNames(...inputs);
};

/**
 * 判断字符串是否为 base64 编码格式
 * @param str 待检测字符串
 * @returns 是否为 base64 字符串
 */
export const isBase64 = (str: string): boolean => {
  if (!str || typeof str !== 'string') return false;
  // 检查是否以 data:image/ 开头（常见于图片 base64）
  if (str.startsWith('data:image/')) return true;
  // 检查是否为常见的 base64 字符串（不含 data: 前缀）
  // 允许的字符：A-Z, a-z, 0-9, +, /, =，长度为4的倍数
  const base64Regex = /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/;
  // 一般 base64 字符串长度大于100
  return base64Regex.test(str) && str.length % 4 === 0 && str.length > 100;
};

export const hashStr = (str: string) => {
  return crypto.createHash('sha256').update(str).digest('hex');
};


export const encodeBase64 = (str: string): string => {
  if (typeof btoa !== 'undefined') {
    // 浏览器环境
    return btoa(unescape(encodeURIComponent(str)));
  } else if (typeof Buffer !== 'undefined') {
    // Node.js 环境
    return Buffer.from(str, 'utf8').toString('base64');
  }
  throw new Error('No Base64 encoding method available');
}

export const decodeBase64 = (base64: string): string => {
  if (typeof atob !== 'undefined') {
    // 浏览器环境
    return decodeURIComponent(escape(atob(base64)));
  } else if (typeof Buffer !== 'undefined') {
    // Node.js 环境
    return Buffer.from(base64, 'base64').toString('utf8');
  }
  throw new Error('No Base64 decoding method available');
}